#include "stm32f10x.h"                  // Device header
#include "OLED.h"

#define CLK_PIN GPIO_Pin_5
#define CS_PIN GPIO_Pin_4
#define OUT_PIN GPIO_Pin_7
#define IN_PIN GPIO_Pin_6

void SPI_WriteSS(u8 bit)
{
	GPIO_WriteBit(GPIOA,CS_PIN,(BitAction)bit);
}

void SPI_Periph_Init(void)
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1,ENABLE);
	
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Pin = CS_PIN;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;//推挽输出，强劲动力
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&GPIO_InitStructure);
	
	GPIO_InitStructure.GPIO_Pin = IN_PIN;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;//上拉输入
	GPIO_Init(GPIOA,&GPIO_InitStructure);
	
	GPIO_InitStructure.GPIO_Pin = CLK_PIN | OUT_PIN;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
	GPIO_Init(GPIOA,&GPIO_InitStructure);
	
	SPI_InitTypeDef SPI_InitStructure;
	SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_256;//对72Mhz进行预分频
	SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;//0
	SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;//0
	SPI_InitStructure.SPI_CRCPolynomial = 7;//CRC校验的默认值，不用管
	SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
	SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;//标准模式，即双线全双工
	SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;//高位先行
	SPI_InitStructure.SPI_Mode = SPI_Mode_Master;//指定当前设备为主机
	SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
	SPI_Init(SPI1,&SPI_InitStructure);
	
	SPI_Cmd(SPI1,ENABLE);
	
	SPI_WriteSS(1);
}

void SPI_Periph_Start(void)
{
	SPI_WriteSS(0);
}

void SPI_Periph_Stop(void)
{
	SPI_WriteSS(1);
}
//运算符优先级口诀：乘加移比与异或； 成家宜彼羽翼获
u8 SPI_Periph_SwapByte(u8 b) //模式0，sck低电平时高位数据送至引脚，sck高电平时读取引脚数据送至最低位
{
	while(SPI_I2S_GetFlagStatus(SPI1,SPI_I2S_FLAG_TXE) != SET);
	SPI_I2S_SendData(SPI1,b);
	while(SPI_I2S_GetFlagStatus(SPI1,SPI_I2S_FLAG_RXNE) != SET);
	return SPI_I2S_ReceiveData(SPI1);
}
